#!/usr/bin/env python
#coding=utf-8

import time, os, xlrd
from decimal import Decimal
import calendar
from hashlib import sha256
from datetime import datetime, date
from xpinyin import Pinyin
from flask import Blueprint, g, request, redirect, url_for, render_template, make_response, session, current_app
from flask.ext.sqlalchemy import Pagination
from sqlalchemy import not_, or_

from codingabc.database import db
from codingabc.response import ResponseJson
from codingabc.helpers import log_debug, log_info, log_error, toint, get_count, randomstr, ismobile, format_timestamp, isemail

from app.helpers.user import get_uid
from app.helpers.common import menu, list_pagination

from app.models.user import User, UserAdmin, UserPassword
from app.models.role import Role, RoleMenu
from app.services.get_data import get_role_list, user_role_id_list
from app.services.user import UserService

user = Blueprint('user', __name__)
resjson = ResponseJson()
resjson.module_code = 11
us = UserService()


@user.route('/')
@user.route('/<int:page>')
@user.route('/<int:page>-<int:page_size>')
def index(page=1, page_size=20):
    """会员列表"""
    g.page_type = 'search'
    g.title = u'会员列表'

    args     = request.args
    keyword     = args.get('keyword', '').strip()
    search_type = toint(args.get('search_type', '1'))
    cs_id       = toint(args.get('cs_id', '0'))
    is_export   = toint(args.get('is_export', '0'))
    uid_id_str  = args.get('uid_id_str', '').strip()
    id_list_str = args.get('id_list_str', '').strip().strip(',')
    role_name   = session.get('role_name', '')
    school_name = args.get('school_name', '')

    teacher_uid_list = db.session.query(User.uid).\
                            filter(User.uid == UserAdmin.uid).\
                            filter(UserAdmin.role_id == Role.role_id).\
                            filter(Role.role_name == u'老师').all()

    q = User.query.filter(User.founder != '').\
            filter(not_(User.uid.in_(teacher_uid_list)))

    if search_type == 1:
        q = q.filter(User.nickname.like(u'%'+ keyword + u'%'))

    if search_type == 2:
        q = q.filter(User.mobile.like(u'%'+ keyword + u'%'))

    if search_type == 3:
        q = q.filter(User.id_no.like(u'%'+ keyword + u'%'))

    if cs_id > 0:
        q = q.filter(User.cs_id == cs_id)

    if role_name == u'老师':
        cs_id = session.get('cs_id')
        q = q.filter(User.cs_id == cs_id)

    if school_name:
        q = q.filter(User.school_name.like('%' + school_name + '%'))

    if is_export == 1:
        uid_list = id_list_str.split(',')
        user_list = q.filter(User.uid.in_(uid_list)).\
                    order_by(User.uid.asc()).all()

        return UserService()._user_export_data(user_list)

    user_list  = q.order_by(User.uid.desc()).offset((page-1)*page_size).\
                    limit(page_size).all()
    user_list = user_list if user_list else []

    pagination  = Pagination(None, page, page_size, q.count(), None)
    res = make_response(render_template('user/index.html.j2', **locals()))
    res.set_cookie('goback_url', request.url)

    return res


@user.route('/change_role')
def change_role():
    """角色切换"""

    role_id = toint(request.args.get('role_id', '0'))
    uid     = session.get('uid')
    if role_id <= 0:
        return u'参数出错'

    role = Role.get(role_id)

    if not role and role_id != 1:
        return u'切换的角色不存在'

    role_id_list = user_role_id_list(uid)
    role_id_list.remove(role_id) #去除角色列表中的已切换的角色
    session['menu'] = menu(role_id)
    session['role_id'] = role_id
    session['role_name'] = u'超级管理员' if role_id == 1 else role.role_name
    session['role_temp_list'] = get_role_list(role_id_list)

    return u'ok'

